package bible.sunflower.web.filter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class CharacterEncodingFilter implements Filter {

	Logger log = Logger.getLogger( CharacterEncodingFilter.class );
	
	private String character = "UTF-8";
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {		
		if ((request instanceof HttpServletRequest)) {
		      HttpServletRequest req = (HttpServletRequest)request;
		      HttpServletResponse resp = (HttpServletResponse)response;
		      String url = req.getRequestURI();

		      if (url.indexOf("%") != -1){
		    	  try {
			          String imgType = "";
			          if (url.toLowerCase().endsWith(".jpg")){
			            imgType = "jpeg";
			          }else if (url.toLowerCase().endsWith(".gif")){
			            imgType = "png";
			          }else if (url.toLowerCase().endsWith(".bmp")){
			            imgType = "bmp";
			          }else if (url.toLowerCase().endsWith(".png")){
			            imgType = "png";
			          }
			          if (!"".equals(imgType)) {
			             url = URLDecoder.decode(url, "UTF-8");
			             File img = new File(req.getRealPath("/") + url.substring(url.indexOf("/") - 1));
			             if (img.exists()) {
			               BufferedImage bufi = ImageIO.read(img);
			               resp.reset();
			               resp.setContentType("image/" + imgType);
			               ImageIO.write(bufi, imgType, resp.getOutputStream());
			             }
			             return;
			          }
			       }catch (Exception localException) {
			          log.error("character exception", localException);
			       }
		      }
		      String urlEncode = request.getParameter("urlEncode");
		      if ((urlEncode != null) && (!"".equals(urlEncode))){
		          request.setCharacterEncoding(urlEncode);
		      }else{
		          request.setCharacterEncoding(character);
		          response.setCharacterEncoding( character );
		      }
		}else{
		    request.setCharacterEncoding( character );
		    response.setCharacterEncoding( character );
		}
	   chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {		
		character = config.getInitParameter("character");
		log.debug("filter character : " + character );
	}

}
